package com.wang.cloud.manage.convert;

import com.wang.cloud.manage.domain.co.MenuAddCo;
import com.wang.cloud.manage.domain.co.MenuUpdateCo;
import com.wang.cloud.manage.domain.entity.MenuEntity;
import com.wang.cloud.manage.domain.vo.MenuPageVo;
import com.wang.cloud.manage.domain.vo.MenuTreeVo;
import com.wang.cloud.manage.domain.vo.MenuVo;
import org.mapstruct.Mapper;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 系统-菜单权限表
 * </p>
 *
 * @author wy
 * @since 2024-07-15
 */
@Mapper(componentModel = "spring")
public interface MenuConvertor {

    MenuEntity addCoToEntity(MenuAddCo addCo);

    MenuEntity updateCoToEntity(MenuUpdateCo addCo);

    MenuPageVo entityToPageVo(MenuEntity entity);

    MenuVo entityToVo(MenuEntity entity);

    MenuTreeVo entityToTreeVo(MenuEntity entity);


    /**
     * 构建菜单树
     *
     * @param list
     * @return
     */
    default List<MenuTreeVo> buildTree(List<MenuEntity> list) {
        Map<Long, List<MenuTreeVo>> map = list.stream()
                .map(this::entityToTreeVo)
                .collect(Collectors.groupingBy(MenuTreeVo::getParentId));
        List<MenuTreeVo> topList = map.getOrDefault(0L, Collections.emptyList());
        for (MenuTreeVo parent : topList) {
            buildTree(parent, map);
        }
        return topList;
    }

    default void buildTree(MenuTreeVo parent, Map<Long, List<MenuTreeVo>> map) {
        if (Objects.isNull(parent)) {
            return;
        }
        List<MenuTreeVo> menuTreeVos = map.getOrDefault(parent.getId(), Collections.emptyList());
        parent.setChildren(menuTreeVos);
        parent.setChildNodesNum(menuTreeVos.size());
        for (MenuTreeVo menuTreeVo : menuTreeVos) {
            buildTree(menuTreeVo, map);
        }
    }
}
